/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jule.clases;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.AbstractCollection;
import java.util.Iterator;
import javax.swing.text.JTextComponent;

/**
 *
 * @author Administrador
 */
public class util {

    // clases utiles para acceder...
    public static String userHome = "";
    public static String fileSeparator = "";
    public static String templatesDirectory = "";
    public static String projectsDirectory = "";
    public static String templateProjectsDirectory = "";
    public static String confDirectory = "";
    //System.getProperty("os.name").contains("windows")
    //System.getenv("windir")

    public util() {


        fileSeparator = System.getProperty("file.separator");


        // using application directory....
        // userHome = "."; // using application directory

        // using home directory...
        userHome = System.getProperty("user.home");
        userHome = userHome + fileSeparator + "jule";

        templateProjectsDirectory = userHome + fileSeparator + "projectTemplates";
        templatesDirectory = userHome + fileSeparator + "templates";
        projectsDirectory = userHome + fileSeparator + "projects";
        confDirectory = userHome + fileSeparator + "conf";


    }

    // las funciones para crear los directorios iniciales...
    /**
     * Creates the directory where the uleule files will be written.
     * The "lf5" directory is created in the Documents and Settings
     * directory on Windows 2000 machines and where ever the user.home
     * variable points on all other platforms.
     */
    public static void createUleUleDirectory() {
       File f = new File(userHome);
        if (!f.exists()) {
            try {
                f.mkdir();
            } catch (SecurityException e) {
                e.printStackTrace();
            }
        }

    }

    public static void createTemplatesDirectory() {
         File f = new File(templatesDirectory );
        if (!f.exists()) {
            try {
                f.mkdirs();
            } catch (SecurityException e) {
                e.printStackTrace();
            }
        }

    }

    public static void createProjectTemplatesDirectory() {
         File f = new File(templateProjectsDirectory);
        if (!f.exists()) {
            try {
                f.mkdirs();
            } catch (SecurityException e) {
                e.printStackTrace();
            }
        }

    }

    public static void createProjectsDirectory() {
         File f = new File(projectsDirectory);
        if (!f.exists()) {
            try {
                f.mkdirs();
            } catch (SecurityException e) {
                e.printStackTrace();
            }
        }

    }

    public static void createConfDirectory() {
         File f = new File(confDirectory);
        if (!f.exists()) {
            try {
                f.mkdirs();
            } catch (SecurityException e) {
                e.printStackTrace();
            }
        }

    }
    // used to combine two paths ...

    public static String combinePaths(String path1, String path2) {
        path1 = path1.replace("/", "\\");
        path2 = path2.replace("/", "\\");
        if (!path1.endsWith("\\")) {
            path1 = path1.concat("\\");
        }
        if (path2.startsWith("\\")) {
            path2 = path2.substring(1, path2.length());
        }
        if (!path2.endsWith("\\")) {
            path2 = path2.concat("\\");
        }
        return path1.concat(path2);


    }

    // used to combine one path and a file ...
    public static String combinePathAndFile(String path1, String path2) {
        path1 = path1.replace("/", "\\");
        path2 = path2.replace("/", "\\");
        if (!path1.endsWith("\\")) {
            path1 = path1.concat("\\");
        }
        if (path2.startsWith("\\")) {
            path2 = path2.substring(1, path2.length());
        }

        return path1.concat(path2);


    }

    public static void copyfile(String srFile, String dtFile) {
        try {
            File f1 = new File(srFile);
            File f2 = new File(dtFile);
            f2.createNewFile();
            InputStream in = new FileInputStream(f1);

            //For Append the file.
            // OutputStream out = new FileOutputStream(f2,true);

            OutputStream out = new FileOutputStream(f2, false);

            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
            System.out.println("File copied.");
        } catch (FileNotFoundException ex) {
            System.out.println(ex.getMessage() + " in the specified directory.");
            // System.exit(0);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
    // para saber como cargar un archivo ...

    public static void prueba() {
//             final File dir = new File (System.getProperty("user.home"));
//            store = new File(dir, "prueba.dat");
    }
//     /**
//     * Creates the specified file and writes the supplied contents to it.
//     */
//    protected boolean writeToFile (File tofile, String contents)
//    {
//        try {
//            PrintStream out = new PrintStream(new FileOutputStream(tofile));
//            out.println(contents);
//            out.close();
//            return true;
//        } catch (IOException ioe) {
//             
//            return false;
//        }
//    }

//    public void rellenarCombo(JComboBox combo, enum xenum)
//    {
//         
//      for (FriendType friendType : FriendType.values()) {
//         comboBox.getComboBoxModel().add(friendType.toString(), friendType);
//      }
//    
//    }
//public static JComboBox fillCombo(String strSQL,Connection sCN,String strFieldName){
//		Statement stFC;
//		ResultSet rsFC;
//		String cmbList[] =new String[0];
//		int TotalRow = 0;
//		int rowNum = 0;
//		try{
//			stFC = sCN.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
//			rsFC = stFC.executeQuery(strSQL);
//			rsFC.afterLast();
//			//Get the current record position
//			if(rsFC.previous())TotalRow = rsFC.getRow();
//			//Move back to the first record;
//			rsFC.beforeFirst();
//			if(TotalRow > 0){
//				cmbList = new String[TotalRow];
//				while(rsFC.next()){
//					cmbList[rowNum] = "" + rsFC.getString(strFieldName);
//					rowNum++;
//				}
//			}else{
//				cmbList[0] ="";
//			}
//		}catch(SQLException sqlEx){
//				System.out.println("\nERROR IN clsPublicMethods(fillCombo):" + sqlEx + "\n");
//			}
//		rsFC = null;
//		stFC = null;
//		TotalRow=0;
//		return new JComboBox(cmbList);
//	}
// public void populateCombo(URL[] urls) {
//    // Save existing selection
//    Object o = urlCombo.getSelectedItem();
//    populatingCombo = true;
//    urlCombo.setModel(new DefaultComboBoxModel(urls));
//    // Restore original selection
//    urlCombo.setSelectedItem(o);
//    populatingCombo = false;
//  }
    // para combos...
    // read the file into the pane
    // para cargar un text pane con un archivo...
    static void readin(String fn, JTextComponent pane) {
        try {
            FileReader fr = new FileReader(fn);
            pane.read(fr, null);
            fr.close();
        } catch (IOException e) {
            System.err.println(e);
        }
    }
    // sirve para convertir una coleccion en una cadena con un separador
    // equivalente al c# string.join()

    public static String join(AbstractCollection s, String delimiter) {
        StringBuffer buffer = new StringBuffer();
        Iterator iter = s.iterator();
        if (iter.hasNext()) {
            buffer.append(iter.next());
            while (iter.hasNext()) {
                buffer.append(delimiter);
                buffer.append(iter.next());
            }
        }
        return buffer.toString();
    }

    /** @param filePath the name of the file to open. Not sure if it can accept URLs or just filenames. Path handling could be better, and buffer sizes are hardcoded
     */
    public static String readFileAsString(String filePath)
            throws java.io.IOException {
        StringBuffer fileData = new StringBuffer(1000);
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        char[] buf = new char[1024];
        int numRead = 0;
        while ((numRead = reader.read(buf)) != -1) {
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
            buf = new char[1024];
        }
        reader.close();
        return fileData.toString();
    }

    public static String writeStringAsFile(String filePath, String cadena)
            throws java.io.IOException {
        try {
            File file = new File(filePath);
//            FileWriter fw = new FileWriter(new File(filePath) );
//            fw.write(cadena);
//            fw.flush();
//            fw.close();

            final byte[] utf8_bom = {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF};

            boolean exists = file.isFile();
            OutputStream out = new FileOutputStream(file, false);
            try {
                if (!exists) {
                    // then this is a new file
                    // write the BOM marker
                    out.write(utf8_bom);
                }

                Writer writer = new OutputStreamWriter(out, "UTF-8");
                try {
                    writer.write(cadena);
                } finally {
                    writer.close();
                }
            } finally {
                out.close();
            }

            return "";
        } catch (IOException e) {
            return null;
        }
    }
//    // this function traverses a directory and copy only the directories
//    private void traverseDirectoriesAndCopy(File dir) {
//
//        File targetDirectory = null;
//
//        if (dir.isDirectory()) {
//            txtInfo.append("Found directory : " + dir.getName() + "\n");
//
//            //if not exists then....
//
//            String finalDirectory = null;
//            finalDirectory = dir.getAbsolutePath().replace(txtProjectTemplatesDirectory.getText(), "");
//
//
//            targetDirectory = new File(util.combinePaths(txtDirectory.getText(), finalDirectory));
//            if (targetDirectory.exists()) {
//            } else {
//                targetDirectory.mkdirs();
//                txtInfo.append("Created directory : " + targetDirectory.getName() + "\n");
//            }
//
//
//            String[] children = dir.list();
//            for (int i = 0; i < children.length; i++) {
//                traverseDirectoriesAndCopy(new File(dir, children[i]));
//            }
//        }
//    }
}
